package com.xinghou.platform.server.api.bussiness.impl;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.lucene.main.UserLuceneService;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.api.bussiness.UserInfoBusinessService;
import com.xinghou.platform.server.api.common.ImageComb;
import com.xinghou.platform.server.api.common.XHUrlConst;
import com.xinghou.platform.util.*;
import org.springframework.dao.DataAccessException;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;

import com.xinghou.platform.entity.resp.ShareInfoPhotoResp;
import com.xinghou.platform.entity.resp.ShareInfoResp;
import com.xinghou.platform.entity.resp.UserInfoResp;
import com.xinghou.platform.server.api.bussiness.UserActionBusinessService;
import com.xinghou.platform.server.api.common.Constants;

/**
 * 
 * @author wzk
 *
 */
@Service("userActionService")
public class UserActionBusinessServiceImpl implements UserActionBusinessService {
	@Resource
	private UserDAO userDAO;
	@Resource
	private PhotoDAO photoDAO;
	@Resource 
	private VisitToDAO visitToDAO;
	@Resource 
	private VisitFromDAO visitFromDAO;
	@Resource
	private StoreDAO storeDAO;
	@Resource
	private UserRelationFromDAO userRelationFromDAO;
	@Resource
	private UserRelationToDAO userRelationToDAO;
	@Resource
	private UserGeoDAO userGeoDAO;
	@Resource
	private SharedCardBrowseDAO sharedCardBrowseDAO;
	@Resource
	private SharedCardPraiseDAO sharedCardPraiseDAO;
	@Resource
	private InterestTagsDAO interestTagsDAO;
	@Resource
	private StoreBrowseDAO storeBrowseDAO;
	@Resource
	private CityDAO cityDAO;
	@Resource
	private UserStatisticsDAO userStatisticsDAO;
	@Resource
	private DataConfigDAO dataConfigDAO;
	@Resource
	private UserVisitsDAO userVisitsDAO;

	@Resource
	private UserLuceneService userLuceneService;
	@Resource
	private UserInfoBusinessService userInfoBusinessService;

	private String photouri = ConfigUtil.getProperty("file_download");
	//查询最近来访信息
	@Override
	public List<ShareInfoResp> getVisitToPhoto(int userId,Long time, int rowNum)
			throws DataAccessException {
		List<ShareInfoResp> list = new ArrayList<ShareInfoResp>();
		//获得来访我uesrid集合
		List<VisitTo> visitTolist =  visitToDAO.getVisitToGroupByToUserId(userId, time, rowNum);
		for(VisitTo visitTo : visitTolist)
		{
			ShareInfoResp shareInfoResp = new ShareInfoResp();
			int fromid = visitTo.getFromuserid();
			User user= userDAO.getUserById(fromid);
			shareInfoResp.setUserid("");
			shareInfoResp.setSimphotourl("");
			shareInfoResp.setPhotourl("");
			if(user != null){
				Photo photo = photoDAO.getPhotoById(user.getHeadid());
				shareInfoResp.setUserid(String.valueOf(fromid));
				if(photo != null){
					shareInfoResp.setSimphotourl(PhotoPathUtil.getDB160(photouri+photo.getPhotoUri()));
					shareInfoResp.setPhotourl(photouri+photo.getPhotoUri());
					if((photo.getPhotoUri()+"/").indexOf("//")>0){
						shareInfoResp.setSimphotourl(PhotoPathUtil.getDB160(photouri+photo.getPhotoUri()));
						shareInfoResp.setPhotourl(photouri+photo.getPhotoUri());
					}
				}else{
					System.out.println("photot is null"+user.getUserid());
				}
			}
			
			list.add(shareInfoResp);
		}
		return list;
	}

	//查询最近来访信详细息列表
	@Override
	public List<UserInfoResp> getVisitToOrFromList(int userId, int type,Long time, int rowNum) throws DataAccessException {
		List<UserInfoResp> list = new ArrayList<UserInfoResp>();
		time=System.currentTimeMillis();
		//获得来访我uesrid集合

		UserVisits userVisits =userVisitsDAO.getUserVisitsById(userId);
		if(userVisits!=null&&userVisits.getVisits()!=null) {
			JSONArray jsonArray = JSONArray.parseArray(userVisits.getVisits());
			for(int i =0;i<jsonArray.size();i++){
				commFunction1(jsonArray.getInteger(i), userId, list);
			}
			/*List<VisitTo> visitTolist =  visitToDAO.getVisitToGroupByToUserId(userId, time, rowNum);
			for (VisitTo visitTo : visitTolist) {
				commFunction(visitTo.getFromuserid(), userId, list);
			}*/
		}
		return list;
	}
	
	//点赞和浏览用户列表
	@Override
	public List<UserInfoResp> getBrowseAndPraiseList(int userId, int shareid,int sharetype, int querytype, String fromno,int rowNum,int showtype)
			throws DataAccessException {
		List<UserInfoResp> list = new ArrayList<UserInfoResp>();
	 if(sharetype==Constants.SHARECARD || sharetype==Constants.REQUESTCARD)//分享卡或求卡
		{
			if(querytype==Constants.BROWSE)	//浏览
			{
				List<SharedCardBrowse> shareBrowseslist = sharedCardBrowseDAO.getListByCardidTime(shareid, Timestamp.valueOf(fromno), rowNum);
				for(SharedCardBrowse sharedCardBrowse : shareBrowseslist)
				{
					getCommBrewsePraise(list,sharedCardBrowse.getUserId(),sharedCardBrowse.getUpdateTime(),showtype,-1);
				}
			}else if(querytype==Constants.PRAISE){//点赞
				List<SharedCardPraise> sharePraiselist = sharedCardPraiseDAO.getShareCardPreiseListByCardid(shareid, Integer.valueOf(fromno), rowNum);
				for(SharedCardPraise sharedCardPraise : sharePraiselist)
				{
					getCommBrewsePraise(list,sharedCardPraise.getUserId(),sharedCardPraise.getCreateTime(),showtype,sharedCardPraise.getId());
				}
			}
		}else if(sharetype == Constants.STORE)//浏览门店
		{
			if(querytype==Constants.BROWSE)	//浏览
			{
				//System.out.println("shareid:"+shareid);
				List<StoreBrowse> storeBrowseslist = storeBrowseDAO.getStoreListByUserId(shareid, rowNum);
				for(StoreBrowse storeBrowse : storeBrowseslist)
				{
					getCommBrewsePraise(list,storeBrowse.getUserId(),storeBrowse.getUpdateTime(),showtype,-1);
				}
			}
		}
		return list;
	}

	//邻友、手艺人、关注信息查询列表
	@Override
	public List<UserInfoResp> getNearuserAndShopInfoList(int userId,int shopid, int sftype, int type, String fromno, int rowNum,String longitude,String latitude)
			throws DataAccessException {
		List<UserInfoResp> list = new ArrayList<UserInfoResp>();
		User user = userDAO.getUserById(userId);
		if(user == null)
		{
			return list;
		}
		long a=System.currentTimeMillis();
		UserGeo userGeo = userGeoDAO.getUserGeoById(user.getUserid());
		long b=System.currentTimeMillis();
		System.out.print("userGeoDAO.getUserGeoById"+(b-a));
		boolean falg = true;
		if(userGeo != null){
			if(StringUtils.isBlank(userGeo.getLongitude().toString())&&StringUtils.isBlank(userGeo.getLatitude().toString())){
				falg = false;
			}
		}
		Point point = null;
		if(falg){
			point = new Point(userGeo.getLongitude(), userGeo.getLatitude());
		}
		if(null != longitude && null != latitude && Double.valueOf(longitude)>0 && Double.valueOf(latitude)>0)
		{
			point = new Point(Double.valueOf(longitude),Double.valueOf(latitude));
		}
		if(type==1)//用户查询
		{
			if(sftype==Constants.FEIEND || sftype==Constants.ARTIST_USER){//附近用户
				//获得附近用户列表
				List<User> usergeolist = new ArrayList<User>();
				if(falg){
					try {
						int usertype=sftype==1?0:1;
						usergeolist=userLuceneService.getSearchUserInfos(null,Integer.parseInt(fromno),rowNum,usertype+"",null,5d, point.getX(),point.getY());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(usergeolist.size()<=0)
				{
					String citycode = user.getCitycode();
					if(citycode!=null)//根据城市经纬度获得附近的用户
					{
						City city = cityDAO.getNameByCode(citycode);
						point = new Point(city.getLongitude(),city.getLatitude());
						long c=System.currentTimeMillis();
						int usertype=sftype==1?0:1;
						try {
							usergeolist=userLuceneService.getSearchUserInfos(null,Integer.parseInt(fromno),rowNum,usertype+"",null,10d, point.getX(),point.getY());
						} catch (IOException e) {
							e.printStackTrace();
						}
						long d=System.currentTimeMillis();
						System.out.print("userLocationMONGO.nearSphere"+(d-c));
					}else{//得到最近登录用户
						List<UserStatistics> userStatistics = userStatisticsDAO.getUserStatisticsLists(rowNum, Timestamp.valueOf(DateUtils.getCurDateTime()));
						for(UserStatistics uStatistics : userStatistics)
						{
							int statid = uStatistics.getStatid();
							User u = userDAO.getUserById(statid);
							commFunction(u.getUserid(),userId,list);
						}
					}
				}
				long a1=System.currentTimeMillis();
				if(usergeolist.size() > 0){
					
					for(User geo:usergeolist){
						commFunction(geo.getUserid(),userId,list);
					}
				}
				long b1=System.currentTimeMillis();
				System.out.print("usergeolist--haha="+(b1-a1));
			}
			else if(sftype==Constants.ATTEN){//关注的人
				List<UserRelationFrom> relationfromlist = userRelationFromDAO.getUserRelationFromList(userId, Timestamp.valueOf(fromno), rowNum);
				for(UserRelationFrom userRelationFrom : relationfromlist)
				{
					//int fid = userRelationFrom.getId();//分页用
					int uid = userRelationFrom.getTouserid();
					User user2 = userDAO.getUserById(uid);
					if(user2.getUsertype()==(Constants.GENNERAL_USER-1)){
						commFunction(uid,userId,list);
					}
				}
			}else if(sftype==5){//粉丝
				List<UserRelationTo> relationfromtolist = userRelationToDAO.getUserRelationToList(userId, Timestamp.valueOf(fromno), rowNum);
				for(UserRelationTo userRelationTo : relationfromtolist)
				{
					commFunction(userRelationTo.getFromuserid(),userId,list);
				}
			}
		}
		return list;
	}
	
	//将点赞与浏览表公共方法抽出来
	private void getCommBrewsePraise(List<UserInfoResp> list,int uid,Long time,int showtype,int id){
		UserInfoResp userInfoResp = new UserInfoResp();
		User user = userDAO.getUserById(uid);
		userInfoResp.setUserid(String.valueOf(uid));
		
		//System.out.println("uid:"+uid);
		Photo photo = photoDAO.getPhotoById(user.getHeadid());
		if(photo != null)
			userInfoResp.setHeadurl((PhotoPathUtil.getDB160(photouri+photo.getPhotoUri())));
		else
			userInfoResp.setHeadurl("");
		
		if(showtype==0){
			userInfoResp.setNickname(user.getNickname());
			userInfoResp.setSex(String.valueOf(user.getSex()));
			userInfoResp.setHoroscope(Gethoroscope.getConstellation(user.getBirthday()));
			userInfoResp.setDate(time.toString());
		}
		userInfoResp.setMintime(String.valueOf(id));
		list.add(userInfoResp);
	}
	
	//将来访重复方法抽出来
	private void commFunction1(int uid,int userId,List<UserInfoResp> list)
	{
		boolean flag = true;
		UserInfoResp userInfoResp = new UserInfoResp();
		User user = userDAO.getUserById(uid);	//访问我或我访问的userid
		User user2 = userDAO.getUserById(userId);	//当前userid
		if(user==null||user2==null)
			return;

		userInfoResp.setUserid(user.getUserid().toString());
		userInfoResp.setHeadurl(PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user.getHeadurl())));
		userInfoResp.setUserid(String.valueOf(uid));
		userInfoResp.setNickname(user.getNickname());
		userInfoResp.setSex(String.valueOf(user.getSex()));
		userInfoResp.setTaste(user.getTaste());
		if(flag)
			list.add(userInfoResp);
	}

	private void commFunction(int uid,int userId,List<UserInfoResp> list)
	{
		boolean flag = true;
		UserInfoResp userInfoResp = new UserInfoResp();
		User user = userDAO.getUserById(uid);	//访问我或我访问的userid
		User user2 = userDAO.getUserById(userId);	//当前userid
		if(user==null||user2==null)
			return;

		userInfoResp.setUserid(user.getUserid().toString());
		userInfoResp.setHeadurl(ImageComb.combHeaderUrl(user.getHeadurl()));
		userInfoResp.setUserid(String.valueOf(uid));
		userInfoResp.setNickname(user.getNickname());
		userInfoResp.setSex(String.valueOf(user.getSex()));
		userInfoResp.setTaste(user.getTaste());
		userInfoResp.setTastedesc(userInfoBusinessService.getInterestTagsTitleOfUser(user.getTaste()));
		userInfoResp.setIsfollow(userInfoBusinessService.getUserRelation(userId,uid)+"");
		if(flag)
			list.add(userInfoResp);
	}

	public int getVisitCountByUserid(int userId) throws DataAccessException {
		return userStatisticsDAO.getUserStatById(userId).getVisitcount();
	}
}
